// request.js
import axios from 'axios';
import {Message} from "element-ui";

const service = axios.create({
    baseURL: 'http://localhost:8080',
    timeout: 5000,
    withCredentials: true
});

// 请求拦截器
service.interceptors.request.use(config => {
    const token = localStorage.getItem('token');
    if (token) {
        config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
}, error => Promise.reject(error));

// 响应拦截器
service.interceptors.response.use(
    response => {
        const res = response.data;
        if (res.code !== 200) {
            Message.error(res.message); // ✅ 使用 Element Plus 的 ElMessage
            console.log(res.message);
            if (res.code === 401) {
                alert('登录状态已过期，请重新登录');
                localStorage.removeItem('token');
                localStorage.removeItem('user');
                window.location.href = '/login';
            }
            return Promise.reject(new Error(res.message || 'Error'));
        } else {
            return res;
        }
    },
    error => {
        const status = error.response?.status;
        if (status === 401) {
            alert('登录状态已过期，请重新登录');
            localStorage.removeItem('token');
            localStorage.removeItem('user');
            window.location.href = '/login';
        }
        return Promise.reject(error);
    }
);

export default service;
